package com.shuma.upms.logging.consumer;

import com.rabbitmq.client.Channel;
import com.shuma.upms.logging.config.MqConstants;
import com.shuma.upms.logging.domain.dto.OperationLogMessage;
import com.shuma.upms.logging.service.LogPersistenceService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Slf4j
@Component
public class OperationLogConsumer {

    @Autowired
    private LogPersistenceService logPersistenceService;

    @RabbitListener(queues = MqConstants.LOG_QUEUE)
    public void handleLogMessage(OperationLogMessage msgBody, Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("收到一封来自mq的新邮件: {}, Message: {}", deliveryTag, msgBody);

        try {
            logPersistenceService.saveLog(msgBody);
            // 业务处理成功，手动ACK
            channel.basicAck(deliveryTag, false);
            log.info("消息 deliveryTag {} 已成功确认。", deliveryTag);
        } catch (Exception e) {
            log.error("处理消息时发生错误，deliveryTag 为 [{}]，该消息将被拒绝。", deliveryTag, e);
            // 业务处理失败，手动NACK，不重新入队
            channel.basicNack(deliveryTag, false, false);
        }
    }
}